package com.kamistoat.netty.netty.websocket;

import com.kamistoat.netty.netty.heartbeat.HeartServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * Netty WebSocket通信服务端
 */
public class WebSocketServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 之前也说过，WebSocket的握手请求仍然是基于Http协议的，所以仍然会用到H体p编解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 块处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            // 因为Http协议传输过程是分段的，HttpObjectAggregator可以将多个Http段文聚合起来
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            // WebSocketServerProtocolHandler 的核心功能是根据Http协议发送的WebSocket握手请求，将之后的通信协议升级为WebSocket
                            // 内部的 "/connect" 用于映射建立WebSocket的请求路径
                            pipeline.addLast(new WebSocketServerProtocolHandler("/connect"));
                            pipeline.addLast(new WebSocketHandler());
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(10001).sync();
            channelFuture.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
